package top.codedance.iotp.common.util;

public class HexCodec implements ComCodec {
    @Override
    public byte[] toBytes(String command) {
        command = command.replace(" ", "");
        if (command.length() % 2 != 0) {
            throw new RuntimeException("16进制字符串长度必须是偶数才可以转化为对应的字节数组!");
        }
        int len = command.length() / 2;
        char[] chars = command.toCharArray();
        String[] hexes = new String[len];
        byte[] bytes = new byte[len];
        for (int i = 0, j = 0; j < len; i = i + 2, j++) {
            hexes[j] = "" + chars[i] + chars[i + 1];
            bytes[j] = (byte) Integer.parseInt(hexes[j], 16);
        }
        return bytes;
    }

    @Override
    public String toHex(byte[] result) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp;
        for (int i = 0; i < result.length; i++) {
            temp = Integer.toHexString(result[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}
